<?php

require_once dirname(__FILE__) . '/../../public/DAL/SimpleSelect.php';

/**
 * Description of SingleSelect
 *
 * @TODO: agregar  un metodo para agregar una option mas que sea 
 * x ej. "Seleccione".
 * implementar las opciones staticas, x ej. activo
 * @author Rino7
 */
class SingleDropdown extends AbstractComponent {

    /**
     * The group of options of the dropbox 
     * @var array 
     */
    private $_options = array();

    /**
     * The custom query in case of CUSTOM_QUERY is set as source mode
     * @var string 
     */
    private $_sql;

    /**
     * The source where the data will be retrieved from
     * @var string 
     */
    private $_source = "";

    /**
     * The object responsible to fetch the options data from the DB.
     * @var SimpleSelect 
     */
    private $_simpleSelect;

    /**
     * The selected field which will become in the text attribute of the dropbox option
     * @var string 
     */
    private $_optionValueField;

    /**
     * The selected field which will become in the value attribute of the dropbox option
     * @var string 
     */
    private $_optionTextField;

    /**
     * All the option data returned by either source. 
     * @var array 
     */
    private $_optionData;

    /**
     * array que va a contener la información para tomar los datos de la base de datos:
     * Ej: nombre de tabla, campos, etc
     */
    private $_dataBaseSource;
    /**
     * The static data set
     * @example $static = array(
     * 			    array("value" => "S", "text" => "Si"),
     * 			    array("value" => "N", "text" => "No")
     * 		    )
     * @var array 
     */
    private $_staticData;

    const SELECTED_STRING = "selected='selected'";
    const DATABASE_SOURCE = 'DATABASE';
    const STATIC_SOURCE = 'STATIC';

    public function __construct($name = "") {
        parent::__construct($name);
        $this->_saveMode = parent::ONE_TO_ONE;
    }

    /**
     * Establece la fuente de dónde se obtendrán los datos
     * Puede ser: 
     * 	DATABASE: obtendrá los datos de la bbdd, ej.de uso: país de un usuario
     * 		Se requiere establecer la información correspondiente (nombre de la tabla, campos, etc.)
     *  STATIC: obtendrá los datos de una array enviado por parámetro, ej. de uso: los estados de una noticia
     * 		array("SI" => "S", "NO" => "N")
     *  CUSTOM_QUERY: obtendrá los datos de la bbdd con una consulta personalizada 
     *      ej. de query: "SELECT * FROM provincia pr INNER JOIN pais p ON p.id = pr.id_pais"
     *  AJAX: Para selects anidados ej. de uso: Provincias-Paises. // falta desarrollar
     *  
     * @param string $mode 
     */
    public function setSource($source) {
        $this->_source = strtoupper($source);
    }

    /**
     * Establece los campos de referencia de la bbdd para rellenar los atributos de las 'option'
     * @example array(
     *              "value" => "el campo de la bbdd que estará relacionado con el atributo 'value'",
     *         		"text" => "el campo de la bbdd que estará relacionado con el texto de la 'option'",
     *          )
     * @param array $references 
     */
    public function setMapFields(array $references) {
        $this->_dataBaseSource['mappedFields']['value'] = $references["value"];
        $this->_dataBaseSource['mappedFields']['text'] = $references["text"];
        
    }

    /**
     * Set the query data in order to be able to get the options values and text from the db
     * to populate the select element.
     * @example $queryParameters = array("tableName" => "the db table to fetch the data",
     * 					"fields" = array("fieldName" => "fieldAlias") || array("fieldName")
     * 				    )
     * @param array $queryParameters 
     */
    public function setQueryParametersToRetrieveTheOptionData(array $queryParameters) {
        $this->_validateQueryParameters($queryParameters);
    }

    /**
     * @TODO: may be not necessary this method. check Exception
     * Validate the queryParameters set
     * @param array $queryParameters 
     */
    private function _validateQueryParameters(array $queryParameters) {
        if (!is_array($queryParameters)) {
            //throw exception
            die("queryParameters must be an array");
        }
        if (empty($queryParameters)) {
            //throw exception
            die("queryParameters can't be empty");
        }
        if (!is_string($queryParameters["tableName"])) {
            //throw exception
            die("Table name is not a string");
        } 
        if (empty($queryParameters["tableName"])) {
            //throw exception
            die("Table name is empty");
        } else {
            $this->_dataBaseSource['tableName'] = $queryParameters["tableName"];
        }

        if (!is_array($queryParameters["fields"])) {
            //throw exception
            die("Fields must be an array");
        }

        if (empty($queryParameters["fields"])) {
            //throw exception
            die("Fields array can't be empty");
        } else {
            $this->_dataBaseSource['fields'] = $queryParameters["fields"];
        }
    }

    /**
     * Set the entire data to populate the dropdown
     * @example $options = array("value" => "valueData", "text" => "textData")
     * @param array $options 
     */
    public function setStaticData(array $options) {
        $this->_staticData = $options;
    }

    /**
     * Return parsed early set static data needed for the dropdown options 
     * @return array 
     */
    private function _getStaticData() {
        $parsedOptionGroup = array();
        foreach ($this->_staticData as $oneOptionStaticData) {
            $parsedOption = $this->_parseStaticData($oneOptionStaticData);
            array_push($parsedOptionGroup, $parsedOption);
        }
        return $parsedOptionGroup;
    }


    /**
     * Parse the static data set early
     * @param type $staticData
     * @return \stdClass 
     */
    private function _parseStaticData($staticData) {
        $tmpOption = new stdClass();
        $tmpOption->value = $staticData["value"];
        $tmpOption->text = $staticData["text"];
        return $tmpOption;
    }

    /**
     * Fill the options to use in the dropdown. 
     */
    private function _fillOptions() {
        foreach ($this->_optionData as $option) {
            array_push($this->_options, $option);
        }
    }

    public function render() {
        switch (strtoupper($this->_source)) {
        case self::DATABASE_SOURCE:
                $fileName = '_singleDynamicDropdown.phtml';
                break;
            case self::STATIC_SOURCE:
                $fileName = '_singleStaticDropdown.phtml';
                $this->_optionData = $this->_getStaticData();
                $this->_fillOptions();
                break;
            default:
                break;
        }
        ob_start();
        require dirname(__FILE__) . '/' . $fileName;
        $SingleDropdown = ob_get_clean();
        return $SingleDropdown;
    }

}

?>
